package org.school.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.school.entity.Host;
import org.school.entity.User;
import org.school.entity.message;
import org.school.service.HostService;
import org.school.service.UserService;
import org.school.staticException.PasswordIncorrectException;
import org.school.staticException.UserNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@Log4j2
@CrossOrigin
public class LoginController {
    @Resource
private UserService userService;
    @Resource
    private HostService hostService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("loginUser")
    public ResponseEntity login (@RequestBody @Validated User loginUser, BindingResult bindingResult) throws IOException, UserNotFoundException, PasswordIncorrectException {//登录功能
        List<ObjectError> allErrors=bindingResult.getAllErrors();
        allErrors.forEach(error->log.error("用户登录时校验失败:{}",error.getDefaultMessage()));
        if (allErrors.size()>0){
            return  ResponseEntity.status(404).body("msg:登录的用户校验失败，可能用户不存在");
        }
       message userinfo = userService.login(loginUser.getUsername(),loginUser.getPassword());
        return ResponseEntity.ok().body(userinfo);
    }

    @PostMapping("loginHost")
    public ResponseEntity login (@RequestBody
                                       @Validated Host loginHost, BindingResult bindingResult) throws IOException, UserNotFoundException, PasswordIncorrectException {//登录功能
        List<ObjectError> allErrors=bindingResult.getAllErrors();
        allErrors.forEach(error->log.error("用户登录时校验失败:{}",error.getDefaultMessage()));
        if (allErrors.size()>0){
            return  ResponseEntity.status(404).body("mesg:用户不存在");
        }



        message hostMsg = hostService.login(loginHost.getUsername(),loginHost.getPassword());

        return ResponseEntity.ok().body(hostMsg);
    }
}
